import { useState } from 'react'
import classes from './Register.module.css'

const Register = () => {
  const judgeAccount = (account: string) => {
    var regexp = /\\w+@\\w{2,6}(\\.\\w{2,3})+/
    return regexp.test(account)
  }

  const judgePhoneNumber = (phoneNumber: string) => {
    var regexp = /^1[3-9]\d{9}$/
    return regexp.test(phoneNumber)
  }

  const [formData, setFormData] = useState({
    account: '',
    password: '',
    phoneNumber: '',
  })

  const accountRegistHandler = (e: any) => {
    setFormData({
      ...formData,
      account: e.target.value,
    })
  }

  const passwordRegistHandler = (e: any) => {
    setFormData({
      ...formData,
      password: e.target.value,
    })
  }

  const phoneNumberRegistHandler = (e: any) => {
    setFormData({
      ...formData,
      phoneNumber: e.target.value,
    })
  }

  let warnMessage

  if (!judgeAccount(formData.account)) {
    warnMessage = (
      <div className={classes.confirmContent}>请输入正确的邮箱</div>
    )
  } else if (!judgePhoneNumber(formData.phoneNumber)) {
    warnMessage = (
      <div className={classes.confirmContent}>请输入正确的手机号码</div>
    )
  } else {
    warnMessage = <div></div>
  }

  const formSubmitHandler = (e: any) => {
    e.preventDefault()

    const newLog = {
      account: formData.account,
      password: formData.password,
      phoneNumber: formData.phoneNumber,
    }

    console.log(newLog)

    setFormData({
      account: '',
      password: '',
      phoneNumber: '',
    })
  }

  return (
    <div>
      <form onSubmit={formSubmitHandler}>
        <div className={classes.formItem}>
          <label htmlFor="account"></label>
          <input
            id="account"
            type="text"
            onChange={accountRegistHandler}
            value={formData.account}
            placeholder={'请输入邮箱'}
            className={classes.text}
          />
        </div>
        <div className={classes.formItem}>
          <label htmlFor="password"></label>
          <input
            id="password"
            type="text"
            onChange={passwordRegistHandler}
            value={formData.password}
            placeholder={'请输入登录密码'}
            className={classes.text}
          />
        </div>
        <div className={classes.formItem}>
          <label htmlFor="phoneNumber"></label>
          <input
            id="phoneNumber"
            type="text"
            onChange={phoneNumberRegistHandler}
            value={formData.phoneNumber}
            placeholder={'请输入手机号码'}
            className={classes.text}
          />
        </div>
        <div className={classes.tips}>{warnMessage}</div>
        <div className={classes.formBtn}>
          <button className={classes.registButton}>注册</button>
        </div>
      </form>
    </div>
  )
}

export default Register
